package com.msb.mall.auth.controller;

import com.msb.common.constant.SMSConstant;
import com.msb.common.dto.MemberLoginDTO;
import com.msb.common.dto.MemberRegisterDTO;
import com.msb.common.exception.BizCodeEnume;
import com.msb.common.utils.R;
import com.msb.mall.auth.feign.MemberFeignService;
import com.msb.mall.auth.feign.ThirdPartFeignService;
import com.msb.mall.auth.vo.UserRegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/reg")
@Controller
public class RegController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSms(@RequestParam("phone") String phone){

        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if (null != redisCode){
            // 存在验证码
            // 获取对应key的过期时间
            Long expire = redisTemplate.opsForValue().getOperations().getExpire(SMSConstant.SMS_CODE_PERFIX + phone);
            if (expire <= 6000) {
                return R.error(BizCodeEnume.VALUE_SMS_EXCEPTION.getCode(),BizCodeEnume.VALUE_SMS_EXCEPTION.getMsg());
            }
        }

        // 生成随机验证码
        String code = UUID.randomUUID().toString().substring(0,4);
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX+phone,code,60, TimeUnit.SECONDS);
        System.out.println("code:"+code);
        thirdPartFeignService.sendSms(phone,code);
        return R.ok();
    }

    /**
     * 用户注册
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        HashMap<String, String> map = new HashMap<>();
        if (result.hasErrors()){
            // 校验有错误
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                // 错误的字段
                String field = fieldError.getField();
                // 错误的信息
                String msg = fieldError.getDefaultMessage();
                map.put(field,msg);
            }
            model.addAttribute("error",map);
            return "reg";
        }else {
            // 校验正确，验证验证码是否正确
            String str = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            if (null != str && str.equalsIgnoreCase(vo.getCode())){
                // 校验完成，入库完成注册
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                MemberRegisterDTO memberRegisterDTO = new MemberRegisterDTO();
                BeanUtils.copyProperties(vo,memberRegisterDTO);
                R r = memberFeignService.register(memberRegisterDTO);
                if(r.getCode()==0){
                    return "redirect:http://auth.msb.com/login.html";
                }else {
                    // 注册失败
                    map.put("msg",r.getCode()+":"+r.get("msg"));
                    model.addAttribute("error",map);
                    return "reg";
                }

            }else {
                Long expire = redisTemplate.opsForValue().getOperations().getExpire(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                if (expire<=0){
                    map.put("code","验证码已过期");
                }else {
                    map.put("code","验证码错误");
                }
                model.addAttribute("error",map);
                return "reg";
            }
        }
    }

}
